<template>
  <div>
    <el-upload
      ref="upload"
      :action="upload.url + actionUrl"
      :headers="upload.headers"
      list-type="picture-card"
      :on-success="handleAvatarSuccess"
      :before-upload="beforeAvatarUpload"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :file-list="fileList"
      :disabled="canCommit"
    >
      <i class="el-icon-plus"></i>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>

</template>

<script>
import {getToken} from "@/utils/auth";
export default {
  name : "MySingleImageUploadCommit",
  props: {
    actionUrl:{
      type: String
    },
    pathList:{
      type: String
    },
    canCommit:{
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      upload:{
        url: process.env.VUE_APP_BASE_API ,
        headers: { Authorization: "Bearer " + getToken() },
      }

    };
  },
  computed:{
    fileList(){
      if(this.pathList && this.pathList!=null){
        return [{url :this.upload.url+ this.pathList}];
      }else{
        return [];
      }
    }
  },
  methods: {
    init() {
      this.$refs.upload.clearFiles();
    },
    handleAvatarSuccess(res, file, fileList) {
      console.log(fileList);
      if(fileList.length>1){
        fileList.splice(0,fileList.length-1);
      }
      this.$emit("fileHandle",res.fileName);
    },
    beforeAvatarUpload(file) {
      let fileType = [ "image/bmp", "image/gif", "image/jpg", "image/jpeg", "image/png" ];
      const isImage = fileType.indexOf(file.type)>=0 ;
      const isLt2M = file.size < 2*1024*1024;

      if (!isImage) {
        this.$message.error('上传图片只能是图片格式!');
      }else if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!');
      }

      return isImage && isLt2M;
    },
    handleRemove(file, fileList) {
      if(file.response){
        this.request({
          url: '/common/fileDelete',
          method: 'post',
          data: {
            path:file.response.fileName,
          }
        })
      }
      this.$emit("fileDeleteHandle");
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    }
  }
};
</script>

<style scoped>

</style>
